home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 8573 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.9 KB  |  65 lines

  1. Path: news.th-darmstadt.de!news!enno
  2. From: enno@inferenzsysteme.informatik.th-darmstadt.de (Enno Sandner)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Overloading operator->
  5. Date: 12 Feb 1996 16:05:16 GMT
  6. Organization: Fachbereich Informatik, TH Darmstadt
  7. Distribution: world
  8. Message-ID: <ENNO.96Feb12170516@kitz.inferenzsysteme.informatik.th-darmstadt.de>
  9. References: <4fmpgd$rko@newsbf02.news.aol.com>
  10. NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
  11. In-reply-to: smalherbe@aol.com's message of 12 Feb 1996 02:16:29 -0500
  12.  
  13. In article <4fmpgd$rko@newsbf02.news.aol.com> smalherbe@aol.com (SMalherbe) writes:
  14.  
  15.    I am attempting to implement a standard "indirection via a proxy"
  16.    design pattern. I do this using the textbook overloading operator->
  17.    approach. This works if the proxy (B in my example) is declared to
  18.    be either automatic or static, but not on the heap. This is a
  19.    significant limitation. The problem appears to be that I cannot
  20.    do a "real" dereference and then use my overloaded operator without
  21.    doing it explicitly (ie. "(*B)->"). This seems pretty ugly. Is there
  22.    a way around this or am I missing something?
  23.  
  24.    class A {
  25.       public:
  26.      A () : x (0)  {}
  27.      int f() const {return x;}
  28.       private:
  29.      int x;
  30.    };
  31.  
  32.    class B {
  33.       public:
  34.      B () {aPtr = new A;}
  35.      A *operator->() {return aPtr;}
  36.       private:
  37.      A *aPtr;
  38.    };
  39.  
  40.    main ()
  41.    {
  42.       B  myB;
  43.       B *myBPtr = new B;
  44.  
  45.       myB->f();            // <--- This is OK
  46.       myBPtr->f();         // <--- This produces the following error:
  47.  
  48.       //   proxy.cpp(23:12) : error EDC3079: "f" is not a member of "B".
  49.  
  50.       (*myBPtr)->f();      // <--- Is also OK
  51.    }
  52.  
  53.    Thanks in advance for any advice,
  54.  
  55. You cannot overload the operators for pointers. That's the core of
  56. your problem. However the following snippet is perfectly valid with
  57. the new behavior of 'new':
  58.  
  59.             B& myBRef=*new B;
  60.             myBRef->f();
  61.             delete &myBRef;
  62.  
  63.     Enno
  64.  
  65.